import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import type { UserConfig, ConfigEnv, ProxyOptions } from 'vite';
// @g
import { PUBLIC_PATH } from './src/constant/index';
import { isProd, loadEnv } from './src/utils/vite';

const pathResolve = (dir: string): any => {
    return resolve(__dirname, '.', dir);
};

// 引入 components/svg文件夹中的load.ts文件
import { loadSvg } from './src/components/icon/svg/load';

// https://vitejs.cn/config/
const viteConfig = ({ command, mode }: ConfigEnv): UserConfig => {
    console.log(command, mode, '===');
    const root = process.cwd();
    const env = loadEnv(mode);
    // 基础路径
    const VITE_PUBLIC_PATH = PUBLIC_PATH;
    // 端口
    const VITE_PORT = env.VITE_PORT;

    console.log('mode', mode);
    console.log('环境变量-----VITE_PUBLIC_PATH：', VITE_PUBLIC_PATH);
    console.log('环境变量-----VITE_PORT：', VITE_PORT);
    console.log('文件路径（ process.cwd()）------', root);
    console.log('文件路径（dirname）------', __dirname + '/src');

    const alias: Record<string, string> = {
        '@': pathResolve('./src'),
        assets: pathResolve('./src/assets')
    };

    const proxy: Record<string, string | ProxyOptions> = {};
    proxy[VITE_PUBLIC_PATH + '/api'] = {
        target: 'http://localhost:28080', // 代理接口
        changeOrigin: true,
        rewrite: (path: any) => {
            console.log('请求服务 ', path, '  实际请求服务 ', path);
            return path;
        },
    };

    return {
        plugins: [vue(), loadSvg('./src/assets/icons/', 'svg-icon')],
        root: process.cwd(),
        resolve: { alias },
        base: VITE_PUBLIC_PATH,
        server: {
            host: '0.0.0.0',
            port: VITE_PORT,
            open: false,
            proxy: proxy,
        },
        build: {
            cssCodeSplit: false,
            sourcemap: false,
            outDir: '../src/main/resources/static/GB28181',
            emptyOutDir: true,
            chunkSizeWarningLimit: 1500,
            rollupOptions: {
                output: {
                    manualChunks: {
                        // 分包配置，配置完成自动按需加载
                        vue: ['vue', 'vue-router', 'pinia', 'element-plus'],
                        echarts: ['echarts'],
                    },
                },
            },
        },
    };
};

export default viteConfig;
